package com.hspedu.hspliving.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hspedu.hspliving.commodity.dao.SpuInfoDao;
import com.hspedu.hspliving.commodity.entity.SpuInfoEntity;
import com.hspedu.hspliving.commodity.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.SkuInfoDao;
import com.hspedu.hspliving.commodity.entity.SkuInfoEntity;
import com.hspedu.hspliving.commodity.service.SkuInfoService;

import javax.annotation.Resource;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Resource
    private SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存sku基本信息
     *
     * @param skuInfoEntity
     */
    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * 条件检索+分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SkuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        //id或名称
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> {
                w.eq(SkuInfoEntity::getSkuId, key).or().like(SkuInfoEntity::getSkuName, key);
            });
        }
        //处理分类检索
        String catalogId = (String) params.get("catalogId");
        wrapper.eq(StringUtils.isNotBlank(catalogId)
                && !"0".equalsIgnoreCase(catalogId), SkuInfoEntity::getCatalogId, catalogId);
        //处理品牌检索
        String brandId = (String) params.get("brandId");
        wrapper.eq(StringUtils.isNotBlank(brandId)
                && !"0".equalsIgnoreCase(brandId), SkuInfoEntity::getBrandId, brandId);
        //处理价格区间检索
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if (StringUtils.isNotBlank(min) && StringUtils.isNotBlank(max)
                && Integer.parseInt(max) >= Integer.parseInt(min)) {
            wrapper.ge(SkuInfoEntity::getPrice, min).le(SkuInfoEntity::getPrice, max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 返回购买用户检索结果-用户前端
     *
     * @param params
     * @return
     */
    @Override
    public SearchResult querySearchPageByCondition(Map<String, Object> params) {

        // v2 查询到状态为[上架]的spu集合
        List<SpuInfoEntity> spuInfoEntities = spuInfoDao.selectList(new LambdaQueryWrapper<SpuInfoEntity>()
                .eq(SpuInfoEntity::getPublishStatus, 1));
        //v2.1 收集spuid
        List<Long> spuIds = spuInfoEntities.stream().map(
                SpuInfoEntity::getId).collect(Collectors.toList());

        //构建检索条件
        LambdaQueryWrapper<SkuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        //将 spuIds 加入到分页条件中去
        if (spuIds.size() > 0 && spuIds != null) {
            queryWrapper.in(SkuInfoEntity::getSpuId,spuIds);
        }else { //没有上架商品
            //没有任何上架的家居商品, 构造一个结果返回，注意不能直接返回null
            //因为前台要解析的.
            SearchResult searchResult = new SearchResult();
            searchResult.setCommodity(new ArrayList<>());
            searchResult.setPageNum(1);
            searchResult.setTotal(0L);
            searchResult.setTotalPages(0);
            searchResult.setPageNavs(new ArrayList<>());
            //设置keyword
            searchResult.setKeyword(params.get("keyword") == null
                    ? "" : params.get("keyword").toString());
            return searchResult;
        }
        //检索词
        String keyword = (String) params.get("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq(SkuInfoEntity::getSkuId,keyword)
                        .or().like(SkuInfoEntity::getSkuName,keyword);
            });
        }
        //分类
        String catalog3Id = (String) params.get("catalog3Id");
        queryWrapper.eq(StringUtils.isNotBlank(catalog3Id)
                        &&!"0".equalsIgnoreCase(catalog3Id),
                SkuInfoEntity::getCatalogId,catalog3Id);
        //品牌
        String brandId = (String) params.get("brandId");
        queryWrapper.eq(StringUtils.isNotBlank(brandId)
                        && !"0".equalsIgnoreCase(brandId),
                SkuInfoEntity::getBrandId,brandId);

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        //二次封装vo
        SearchResult searchResult = new SearchResult();
        searchResult.setCommodity((List<SkuInfoEntity>)pageUtils.getList());
        searchResult.setPageNum(pageUtils.getCurrPage());
        searchResult.setTotal((long)pageUtils.getTotalCount());
        searchResult.setPageNum(pageUtils.getCurrPage());
        searchResult.setTotalPages(pageUtils.getTotalPage());

        List<Integer> pageNavs = new ArrayList<>();
        //遍历总页数，得到分页导航条数据
        for (int i = 1; i <= pageUtils.getTotalPage(); i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        //设置keyword
        searchResult.setKeyword(params.get("keyword") == null
                ? "" : params.get("keyword").toString());
        return searchResult;
    }


}
